import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

export const useAppStore = defineStore('app', () => {
  // 用户状态
  const user = ref<{
    isLoggedIn: boolean
    name?: string
    avatar?: string
    token: string
  }>({
    isLoggedIn: false,
    name: '',
    avatar: '',
    token: ''
  })
  
  // 登录方法
  const login = (name: string, token: string, avatar?: string) => {
    user.value = {
      isLoggedIn: true,
      name,
      token,
      avatar: avatar || ''
    }
    localStorage.setItem('token', token)
  }
  
  // 登出方法，支持传入router参数
  const logout = (showLoginModal = false, router?: any) => {
    user.value = {
      isLoggedIn: false,
      name: '',
      avatar: '',
      token: ''
    }
    localStorage.removeItem('token')
    // 跳转到首页（SPA，不刷新页面）
    if (router) {
      router.push('/')
    }
    // 被动登出才弹出登录框
    if (showLoginModal) {
      ElMessage.error('登录已过期，请重新登录')
      setTimeout(() => {
        window.dispatchEvent(new CustomEvent('show-login-modal'))
      }, 100)
    }
  }
  
  // 公告状态
  const announcement = ref({
    title: '系统维护通知',
    content: '本周六凌晨2-4点系统升级，期间暂停服务',
    visible: true
  })
  
  // 关闭公告
  const closeAnnouncement = () => {
    announcement.value.visible = false
  }
  
  return {
    announcement,
    closeAnnouncement,
    user,
    login,
    logout
  }
}, {
  persist: true
})
